﻿using System;
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using NUglify.Helpers;
using Swashbuckle.AspNetCore.SwaggerGen;
using Swashbuckle.AspNetCore.SwaggerUI;
using Unchase.Swashbuckle.AspNetCore.Extensions.Extensions;
using Unchase.Swashbuckle.AspNetCore.Extensions.Options;

namespace Jy.Abp.AspNetCore.Swagger;

public static class SwaggerExtensions
{
    /// <summary>
    /// 默认配置
    /// </summary>
    public static void ConfigureDefault(this SwaggerGenOptions options)
    {
        foreach (var group in SwaggerHelper.Groups)
            options.SwaggerDoc(group.Key, new OpenApiInfo { Title = group.Value, Version = "v1" });

        options.DocInclusionPredicate((docName, description) =>
        {
            return SwaggerHelper.CheckGroup(docName, description.ActionDescriptor.AsControllerActionDescriptor());
        });

        //options.UseAllOfToExtendReferenceSchemas();

        //获取执行目录下的所有解释文件.xml
        var xmlCommentsFiles = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.xml");
        xmlCommentsFiles.ForEach(file =>
        {
            options.IncludeXmlCommentsWithRemarks(file, true);
        });
        //options.DocumentFilter<AppendActionCountToTagSummaryDocumentFilter>("(count: {0})");
        options.UserFriendlyEnums();
        options.AddEnumsWithValuesFixFilters(opts =>
        {
            opts.IncludeXEnumRemarks = true;
            opts.IncludeDescriptions = true;
            xmlCommentsFiles.ForEach(file =>
            {
                opts.IncludeXmlCommentsFrom(file);
            });
            opts.DescriptionSource = DescriptionSources.DescriptionAttributesThenXmlComments;
        });

        options.CustomSchemaIds(type => type.FullName);
    }

    /// <summary>
    /// UI配置
    /// </summary>
    public static void ConfigureDefault(
        this SwaggerUIOptions options, 
        string applicationName = "web")
    {
        SwaggerHelper.Init(applicationName);

        options.DocumentTitle = $"{SwaggerHelper.ApplicationName} Api Docs";
        foreach (var group in SwaggerHelper.Groups)
        {
            options.SwaggerEndpoint($"{group.Key}/swagger.json", $"{group.Value}");
        }
        options.ConfigObject.PersistAuthorization = true;
    }
}
